<template>
  <el-card v-loading="loading">
    <el-col :span="24">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="$i18n.locale === 'en-US' ? '140px' : '160px'">
        <el-col v-if="this.selectShow" :span="24">
          <el-col :span="12">
            <el-form-item :label="$t('genTable.sourceCode')">
              <!--文本框-->
              <el-select
                v-model="sourceCode"
                placeholder="请选择数据源"
                clearable
                @change="checkSource">
                <el-option
                  v-for="item in dataSourceList"
                  :key="item.dataSourceCode"
                  :label="item.dataSourceName"
                  :value="item.dataSourceCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('genTable.tableList')">
              <!--文本框-->
              <el-select
                v-model="tableCode"
                filterable
                placeholder="请输入关键词"
                clearable
                :filter-method="filterTableList"
                @change="checkTable"
                :loading="selectLoading">
                <el-option
                  v-for="item in tableList"
                  :key="item.tableName"
                  :label="item.tableNameAndComments"
                  :value="item.tableName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('genTable.sourceName')" prop="sourceName">
            <!--文本框-->
            <el-input v-model="dataForm.sourceName" readonly
                      :placeholder="$t('genTable.sourceName')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('genTable.tableName')" prop="tableName">
            <!--文本框-->
            <el-input v-model="dataForm.tableName" readonly
                      :placeholder="$t('genTable.tableName')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('genTable.className')" prop="className">
            <!--文本框-->
            <el-input v-model="dataForm.className"
                      :placeholder="$t('genTable.className')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('genTable.functionName')" prop="functionName">
            <!--文本框-->
            <el-input v-model="dataForm.functionName"
                      :placeholder="$t('genTable.functionName')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('genTable.packageName')" prop="packageName">
            <!--文本框-->
            <el-input v-model="dataForm.packageName"
                      :placeholder="$t('genTable.packageName')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('genTable.moduleName')" prop="moduleName">
            <!--文本框-->
            <el-input v-model="dataForm.moduleName"
                      :placeholder="$t('genTable.moduleName')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-col :span="12">
            <el-form-item :label="$t('genTable.languageFlag')" prop="languageFlag">
              <!--文本框-->
              <el-switch v-model="dataForm.languageFlag"
                         active-text="开"
                         inactive-text="关"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('genTable.tenantFlag')" prop="tenantFlag">
              <!--文本框-->
              <el-switch v-model="dataForm.tenantFlag" active-text="开"
                         inactive-text="关"></el-switch>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('genTable.functionAuthor')" prop="functionAuthor">
            <!--文本框-->
            <el-input v-model="dataForm.functionAuthor" ref="functionAuthor"
                      :placeholder="$t('genTable.functionAuthor')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 子级table名称 -->
          <el-form-item label="选择子表" prop="childTableCode">
            <!--下拉框-->
            <el-select
              v-model="dataForm.childTableCode"
              filterable
              style="width: 100%"
              placeholder="请输入关键词"
              clearable
              :filter-method="filterChildTableList"
              @change="checkChildTable"
              :loading="selectLoading">
              <el-option
                v-for="item in childTableList"
                :key="item.tableName"
                :label="item.tableNameAndComments"
                :value="item.tableName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 子级table名称 -->
          <el-form-item label="关联字段" prop="childFieldCode">
            <!--下拉框-->
            <el-select
              v-model="dataForm.childFieldCode"
              filterable
              style="width: 100%"
              placeholder="关联字段"
              clearable>
              <el-option
                v-for="item in childFieldList"
                :key="item.columnName"
                :label="item.comments"
                :value="item.columnName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('common.remark')" prop="remark">
            <!--文本框-->
            <el-input v-model="dataForm.remark"
                      type="textarea"
                      :autosize="{ minRows: 2, maxRows: 4}"
                      :placeholder="$t('common.remark')"></el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </el-col>

  </el-card>
</template>

<script>
import debounce from 'lodash/debounce'

export default {
  data () {
    return {
      loading: false,
      selectLoading: false,
      dataSourceList: [],
      tableList: [],
      allTableList: [],
      childTableList: [],
      allChildTableList: [],
      childFieldList: [],
      selectShow: true,
      tableCode: '',
      sourceCode: '',
      dataForm: {
        id: '',
        sourceCode: '',
        sourceName: '',
        tableName: '',
        className: '',
        comments: '',
        functionAuthor: '',
        packageName: 'com.uniedp',
        languageFlag: false,
        tenantFlag: false,
        moduleName: '',
        functionName: '',
        childTableCode: '',
        childFieldCode: '',
        remark: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        functionAuthor: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        sourceName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        tableName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        className: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        packageName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        moduleName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        functionName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        languageFlag: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        tenantFlag: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.$nextTick(() => {
        if (this.dataForm.tableName) {
          this.loading = true
          this.getInfo()
          this.selectShow = false
        } else {
          this.$refs['dataForm'].resetFields()
          this.getDataSourceList()
        }
      })
    },
    getDataSourceList () {
      this.$http.get(`/gen/genDataSource/list`).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        // 将arr数组复制给a
        var a = res.data.slice(0)
        // 使用unshift方法向a开头添加item
        a.unshift({ dataSourceCode: 'default', dataSourceName: '默认数据源' })
        this.dataSourceList = a
      }).catch(() => {})
    },
    // 获取table list
    getTableList (dsCode) {
      this.$http.get(`/gen/genTable/tableList?dsCode=${dsCode}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        this.allTableList = res.data
        this.allChildTableList = res.data
        this.tableList = this.allTableList
        this.childTableList = this.allChildTableList
      }).catch(() => {})
    },
    // 选择数据源
    checkSource (val) {
      if (val) {
        let temp = this.$xeutils.find(this.dataSourceList, item => item.dataSourceCode === val)
        this.dataForm.sourceCode = temp.dataSourceCode
        this.dataForm.sourceName = temp.dataSourceName
        this.getTableList(val)
      }
    },
    // 选择表
    checkTable (val) {
      let tableInfo = this.allTableList.filter((value, index, array) => {
        return value.tableName === val
      })
      if (tableInfo.length > 0) {
        this.dataForm.comments = tableInfo[0].comments
        this.dataForm.className = tableInfo[0].className
        this.dataForm.tableName = tableInfo[0].tableName
        this.dataForm.functionName = tableInfo[0].comments
        this.dataForm.moduleName = val.split('_')[0].toLowerCase()
      }
      this.$refs.functionAuthor.focus()
    },
    checkChildTable (val) {
      if (val) {
        if (val === this.dataForm.tableName) {
          this.dataForm.childTableCode = ''
          return this.$message.error('主子表不能为同一个表')
        }
        let tableInfo = this.allTableList.filter((value, index, array) => {
          return value.tableName === val
        })
        this.getChildFieldList(tableInfo[0].tableName)
      }
    },
    getChildFieldList (tableCode) {
      this.loading = true
      this.$http.get(`/gen/genTableColumn/listByTableCode?dsCode=${this.dataForm.sourceCode}&tableCode=${tableCode}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return false
        }
        this.childFieldList = res.data
      }).catch(() => {})
    },
    filterChildTableList (query) {
      this.selectLoading = true
      if (query) {
        this.childTableList = this.allChildTableList.filter((value, index, array) => {
          return value.tableName.indexOf(query) !== -1
        })
      } else {
        this.childTableList = this.allChildTableList
      }
      this.selectLoading = false
    },
    filterTableList (query) {
      this.selectLoading = true
      if (query) {
        this.tableList = this.allTableList.filter((value, index, array) => {
          return value.tableName.indexOf(query) !== -1
        })
      } else {
        this.tableList = this.allTableList
      }
      this.selectLoading = false
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/gen/genTable/genInfo?dsCode=${this.dataForm.sourceCode}&tableName=${this.dataForm.tableName}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.getTableList(res.data.sourceCode)
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.loading = true
        this.$http[!this.dataForm.id ? 'post' : 'put']('/gen/genTable/', this.dataForm).then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return false
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.dataForm = {
                ...this.dataForm,
                ...res.data
              }
              this.selectShow = false
              this.$emit('setActiveName', 'parent', this.dataForm.sourceCode, this.dataForm.tableName, this.dataForm.childTableCode)
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
